﻿using System;
using System.Collections.Generic;
using HyEduOnline.Entities;
using HyEduOnline.Server.Admin;
using HyEduOnline.Server.Common;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSite.Areas.WebApi.Controllers;
using System.Text;
using WebSite.Models;
using HyEduOnline.Server.Teacher;
using HyEduOnline.Models;
using System.IO;
using System.Web.Http;
using System.Net;
using System.Net.Http;
using HyEudOnline.Server.Common;

namespace WebSite.Areas.WebApi.Controllers
{
    public class ResourceController : TeaSourceController
    {
        private TeaSourceDictDAO teaSourceDictDAO = new TeaSourceDictDAO();
        private TeaSourceDAO teaSourceDAO = new TeaSourceDAO();
        private TeaPublicSourceDictDAO teaPublicSourceDictDAO = new TeaPublicSourceDictDAO();
        private TeaPublicSourceDAO teaPublicSourceDAO = new TeaPublicSourceDAO();
        private SysLogDAO _logDao = new SysLogDAO();

        private int CurrentUserID = frontCurrentTea.GetUserID();//取当前登录用户ID
        private string CurrentUserName = frontCurrentTea.GetUserName();//取得当前登录的用户名
        private const string FilePath = "/Upload/Resource/";//上传文件的存储路径

        #region 教师个人资源管理
        /// <summary>
        /// 合并文件和文件夹
        /// </summary>
        /// <param name="IParentId">当前父节点下的所有</param>
        /// <returns></returns>
        public List<ResourceManage> Merge(int IParentId)
        {
            List<ResourceManage> list = new List<ResourceManage>();
            //获取当前文件夹下的文件夹
            TList<TbTeaSourceDict> DictList = teaSourceDictDAO.GetByPage("I_ParentId=" + IParentId + "and I_OwnerUserID=" + CurrentUserID, 0, int.MaxValue);
            foreach (var item in DictList)
            {
                ResourceManage temp = new ResourceManage();
                //将每个文件夹添加到新类列表
                temp.Id = item.Id;
                temp.IParentId = (int)item.IParentId;
                temp.ILevel = (int)item.ILevel;
                temp.IOwnerUserId = CurrentUserID;
                temp.SSourceName = item.SDicName;
                temp.FileType = 0;
                list.Add(temp);
            }
            //查找当前文件夹下的文件,若0层，没有文件    

            TList<TbTeaSource> SourceList = teaSourceDAO.GetByPage("I_TeaSourceDictID=" + IParentId, 0, int.MaxValue);
            foreach (var ite in SourceList)
            {
                //将每个文件添加到新类列表
                ResourceManage temp1 = new ResourceManage();
                ClassValueCopier.Copy(temp1, ite);
                temp1.FileType = 1;
                temp1.IParentId = (int)ite.ITeaSourceDictId;
                list.Add(temp1);
            }
            return list;
        }


        /// <summary>
        /// 重载Merge
        /// </summary>
        /// <param name="dictList">目录列表</param>
        /// <param name="sourList">文件列表</param>
        /// <returns></returns>
        public List<ResourceManage> Merge(TList<TbTeaSourceDict> dictList, TList<TbTeaSource> sourList)
        {
            List<ResourceManage> list = new List<ResourceManage>();
            //遍历所有文件夹
            foreach (var item in dictList)
            {
                ResourceManage temp = new ResourceManage();
                //将每个文件夹添加到新类列表
                temp.Id = item.Id;
                temp.IParentId = (int)item.IParentId;
                temp.ILevel = (int)item.ILevel;
                temp.IOwnerUserId = CurrentUserID;
                temp.SSourceName = item.SDicName;
                temp.FileType = 0;
                list.Add(temp);
            }
            //遍历所有文件
            foreach (var ite in sourList)
            {
                //将每个文件添加到新类列表
                ResourceManage temp1 = new ResourceManage();
                ClassValueCopier.Copy(temp1, ite);
                temp1.FileType = 1;
                temp1.IParentId = (int)ite.ITeaSourceDictId;
                list.Add(temp1);
            }
            return list;
        }


        /// <summary>
        /// 获取当期文件夹下的所有
        /// </summary>
        /// <param name="ID">当期文件夹的ID</param>
        /// <returns></returns>
        public JsonResult GetFile(string SourceName, int ID = 0, int IParentID = -1)
        {
            List<ResourceManage> userList = new List<ResourceManage>();
            int id = IParentID == -1 ? ID : IParentID;
            if (string.IsNullOrEmpty(SourceName))//搜索名字为空
            {
                //取得根目录下的文件
                if (id == 0)
                {
                    TList<TbTeaSource> sourList = teaSourceDAO.GetByPage("I_TeaSourceDictID=0 and I_OwnerUserID=" + CurrentUserID, 0, int.MaxValue);
                    TList<TbTeaSourceDict> dictList = teaSourceDictDAO.GetByPage("I_ParentID=0 and I_OwnerUserID=" + CurrentUserID, 0, int.MaxValue);
                    userList = Merge(dictList, sourList);
                }
                else
                    userList = Merge(id);
            }
            else
            {
                //模糊查询文件夹
                string whereClause1 = "S_DicName like '%" + SourceName + "%' and I_OwnerUserID =" + CurrentUserID;
                TList<TbTeaSourceDict> dictList = teaSourceDictDAO.GetByPage(whereClause1, 0, int.MaxValue);

                //模糊查询文件
                string whereClause2 = "S_SourceName like '%" + SourceName + "%'and I_OwnerUserID =" + CurrentUserID;
                TList<TbTeaSource> sourList = teaSourceDAO.GetByPage(whereClause2, 0, int.MaxValue);

                userList = Merge(dictList, sourList);
            }
            return Json(new
            {
                Data = userList
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 返回上一级
        /// </summary>
        /// <param name="IParentID"></param>
        /// <param name="ID"></param>
        /// <returns></returns>
        public JsonResult GoToParent(int IParentID = -1, int ID = 0)
        {
            //若最后一层，记录下当前文件夹的ID
            if ((IParentID == -1) || (IParentID == 0 && ID != 0))
                IParentID = ID;


            //查找父文件夹
            TbTeaSourceDict dict = teaSourceDictDAO.GetByID(IParentID);


            //修改于1.02日，新增判空操作    by yzp
            if (dict != null)
            {
                //得到父文件夹的IParentId
                int id = int.Parse(dict.IParentId.ToString());

                //得到同一文件夹下的 文件和文件夹
                var userList = Merge(id);
                return Json(new
                {
                    Data = userList
                }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                //没有子节点，返回0层文件
                var list = Merge(0);
                return Json(new
                {
                    Data = list
                }, JsonRequestBehavior.AllowGet);
            }

        }

        /// <summary>
        /// 添加文件夹
        /// </summary>
        /// <param name="SSourceName"></param>
        /// <param name="IParentId"></param>
        /// <param name="ILevel"></param>
        /// <param name="IOwnerUserID"></param>
        /// <returns></returns>
        public int AddFile(string SSourceName, int Id, int IParentId, int ILevel)
        {

            if (ILevel == 0)
            {//0层以下只有文件或空文件夹时
                TbTeaSourceDict dict = teaSourceDictDAO.GetByID(Id);
                if (dict == null)
                {//文件夹已全部删除，新增到0层
                    IParentId = 0;
                    ILevel = 1;
                }
                else
                {
                    ILevel = (int)dict.ILevel + 1;
                }
            }
            try
            {
                TbTeaSourceDict Dict = new TbTeaSourceDict();
                Dict.SDicName = SSourceName;
                Dict.IParentId = IParentId;
                Dict.ILevel = ILevel;
                Dict.IOwnerUserId = CurrentUserID;
                teaSourceDictDAO.Insert(Dict);
                return 1;
            }
            catch (Exception e)
            {

                return 0;
            }
        }

        /// <summary>
        /// 文件夹和文件的删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int DeleteFile(string ids)
        {
            TbSysLog tmpLog = new TbSysLog();
            try
            {
                if (string.IsNullOrEmpty(ids))
                    return 1;//没有选择删除文件或文件夹

                string[] str = ids.Split(new char[] { ',' });
                //拆分字符串，判断文件夹，文件
                foreach (var item in str)
                {
                    string[] FileInfro = item.Split(new char[] { ':' });
                    int id = int.Parse(FileInfro[0]);
                    if (id == 0) continue;
                    if (FileInfro[1].Equals("0"))//文件夹
                    {
                        DeleteSaveFiles(id);
                    }
                    else//文件
                    {
                        TbTeaSource source = teaSourceDAO.GetByID(id);//找到当前文件读出相应信息

                        teaSourceDAO.Del(id);//删除数据库中该文件信息

                        //删除导入到教学资源表中对应的文件
                        TList<TbTeaPublicSource> publicSource = teaPublicSourceDAO.GetByPage("I_TeaSourceID=" + id, 0, int.MaxValue);

                        if (publicSource != null)
                        {
                            teaPublicSourceDAO.Del(publicSource);
                        }
                        //删除文件
                        /*************************************************************/
                        //先在文件里面找到Commonfiles然后删除一条记录，当当前的Count等于0的时候删除Common里面的记录同时删除物理文件
                        //Count等于0代表没有任何用户引用该文件，可以删除物理文件 
                        //Modify By YS
                        int CFId = int.Parse(source.IFileId.ToString());
                        TbCommonFiles TBF = new CommonFilesDAO().GetByID(CFId);
                        CommonFilesDAO CFDAO = new CommonFilesDAO();
                        TBF.ICount--;//将文件使用数量减1
                        //当计数为零的时候删除物理文件
                        if (TBF.ICount == 0)
                        {
                            CFDAO.Del(TBF);                          
                            try
                            {
                                System.IO.File.Delete(Server.MapPath(source.SUrl));//删除物理文件
                                //找到预览文件的相对路径
                                string htmFile = source.SUrl.Replace("/UploadFile/", "/ViewFile/");
                                string htmFilePath = htmFile.Substring(0, htmFile.LastIndexOf(".")) + ".htm";
                                System.IO.File.Delete(Server.MapPath(htmFilePath));//删除相应的预览文件
                            }
                            catch (Exception e)
                            {
                                //将异常信息存入SysLog日志表中 by lx 2015.1.20
                                tmpLog.ILogType = 999;
                                tmpLog.SMessage = "文件资源删除:::::"+e.Message.ToString();
                                _logDao.Insert(tmpLog);
                            }
                        }
                        else
                        {
                            CFDAO.Update(TBF);
                        }
                        //杨爽 ADD end
                        /*************************************************************/

                    }
                }
                return 1;
            }
            catch (Exception e)
            {
                return 0;
            }
        }

        /// <summary>
        /// 文件夹的删除
        /// </summary>
        /// <param name="id"></param>
        public void DeleteSaveFiles(int id)
        {
            TbSysLog tmpLog = new TbSysLog();
            //删除当前文件夹
            teaSourceDictDAO.Del(id);
            //删除当期文件夹下的文件
            TList<TbTeaSource> source = teaSourceDAO.GetByPage("I_TeaSourceDictID=" + id, 0, int.MaxValue);

            foreach (var ite in source)
            {
                //删除教学资源表中对应的文件
                TList<TbTeaPublicSource> publicSource = teaPublicSourceDAO.GetByPage("I_TeaSourceID=" + ite.Id, 0, int.MaxValue);
                if (publicSource != null)
                {
                    teaPublicSourceDAO.Del(publicSource);
                }

                //删除文件
                /*************************************************************/
                //先在文件里面找到Commonfiles然后删除一条记录，当当前的Count等于0的时候删除Common里面的记录同时删除物理文件
                //Modify By YS
                int CFId = int.Parse(ite.IFileId.ToString());
                TbCommonFiles TBF = new CommonFilesDAO().GetByID(CFId);
                CommonFilesDAO CFDAO = new CommonFilesDAO();
                TBF.ICount--;
                //当计数为零的时候删除物理文件
                if (TBF.ICount == 0)
                {

                    try
                    {
                        System.IO.File.Delete(Server.MapPath(ite.SUrl));//删除物理文件
                        CFDAO.Del(TBF);
                        //找到预览文件的相对路径
                        string htmFile = ite.SUrl.Replace("/UploadFile/", "/ViewFile/");
                        string htmFilePath = htmFile.Substring(0, htmFile.LastIndexOf(".")) + ".htm";
                        System.IO.File.Delete(Server.MapPath(htmFilePath));//删除相应的预览文件
                        System.IO.File.Delete(Server.MapPath(ite.SUrl));
                    }
                    catch (Exception e)
                    {
                        //将异常信息存入SysLog日志表中 by lx 2015.1.20
                        tmpLog.ILogType = 999;
                        tmpLog.SMessage = "文件资源删除:::::" + e.Message.ToString();
                        _logDao.Insert(tmpLog);
                    }

                }
                else
                {
                    CFDAO.Update(TBF);
                }
                //删除私人资源表的文件
                teaSourceDAO.Del(ite);
                //循环删除物理文件

            }

            //删除当期文件夹下的文件夹
            TList<TbTeaSourceDict> dict = teaSourceDictDAO.GetByPage("I_ParentID=" + id, 0, int.MaxValue);
            if (dict.Count == 0)
                return;
            else
            {
                teaSourceDictDAO.Del(dict);//删除该文件夹记录
                //删除该文件夹下的对应文件记录
                foreach (var item in dict)
                {
                    DeleteSaveFiles(item.Id);
                }
            }
        }





        /// <summary>
        /// 获取当前节点信息
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public JsonResult currentFile(string keys)
        {
            string[] NodeInfo = keys.Split(new char[] { ':' });
            int id = int.Parse(NodeInfo[0]);
            ResourceManage temp = new ResourceManage();
            if (NodeInfo[1].Equals("0"))//文件夹
            {
                //找到当前文件夹
                TbTeaSourceDict dict = teaSourceDictDAO.GetByID(id);
                temp.Id = dict.Id;
                temp.IParentId = (int)dict.IParentId;
                temp.ILevel = (int)dict.ILevel;
                temp.IOwnerUserId = CurrentUserID;
                temp.SSourceName = dict.SDicName;
                temp.FileType = 0;
            }
            else
            {          //找到当前文件
                TbTeaSource source = teaSourceDAO.GetByID(id);
                ClassValueCopier.Copy(temp, source);
                temp.FileType = 1;
            }
            return Json(temp, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 更新节点
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="res"></param>
        /// <returns></returns>
        public int UpdateFileName(string keys, ResourceManage res)
        {
            try
            {
                if (res.FileType == 0)//文件夹
                {
                    TbTeaSourceDict dict = new TbTeaSourceDict();
                    dict.Id = res.Id;
                    dict.IParentId = (int)res.IParentId;
                    dict.ILevel = (int)res.ILevel;
                    dict.IOwnerUserId = CurrentUserID;
                    dict.SDicName = res.SSourceName;
                    teaSourceDictDAO.Update(dict);
                }
                else
                {
                    TbTeaSource source = new TbTeaSource();
                    ClassValueCopier.Copy(source, res);
                    teaSourceDAO.Update(source);
                }
                return 1;
            }
            catch (Exception e)
            {

                return 0;
            }
        }





        //add by ys
        /// <summary>
        /// 通过MD5值验证该文件是否已存在
        /// </summary>
        /// <param name="Md5Str"></param>
        /// <param name="DictID"></param>
        /// <returns></returns>
        public JsonResult ValidateMD5(string Md5Str, int DictID = 0)
        {

            frontCurrentTea.SetCurrentDictID(DictID);  //保存文件夹的id
            Session["Md5Str"] = Md5Str;
            string whereclause = "S_MD5='" + Md5Str + "'";

            TList<TbCommonFiles> TBF = new CommonFilesDAO().GetByPage(whereclause, 0, int.MaxValue);
            if (TBF.Count > 0)
            {
                TbCommonFiles tempTF = TBF[0];
                string CurrentUserCode = frontCurrentTea.GetNo();//当前登录用户的工号

                //插入到数据库
                TbTeaSource source = new TbTeaSource();
                source.SSourceName = TBF[0].SFileName;
                source.IType = TBF[0].IType;
                source.SSaveName = TBF[0].SSaveName;
                source.SUrl = TBF[0].SUrl;//相对路径
                source.ISize = TBF[0].ISize;
                source.DCreate = DateTime.Now;//获取系统当前时间
                source.ITeaSourceDictId = DictID;
                source.IOwnerUserId = CurrentUserID;
                source.SOwnerName = CurrentUserName;
                source.IFileId = int.Parse(TBF[0].Id.ToString());
                teaSourceDAO.Insert(source);
                //更新CommonFiles count
                CommonFilesDAO CFDAO = new CommonFilesDAO();
                TBF[0].ICount++;
                CFDAO.Update(TBF[0]);

                return Json(1, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(0, JsonRequestBehavior.AllowGet);
            }


        }





        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="DictID">文件夹id，默认不在某个文件夹下</param>
        /// <returns></returns>
        public void ProcessUpload(int DictID)
        {
            string name = Request.Form["name"];  //上传文件的文件名

            string Md5Str = Session["Md5Str"].ToString();
            string CurrentUserCode = frontCurrentTea.GetNo();//当前登录用户的工号
            string imgName = DateTime.Now.ToString("ddHHmmssff");//名称
            string imgType = name.Substring(name.LastIndexOf("."));//类型 .doc
            string webFile = FilePath + CurrentUserCode + "/UploadFile/" + imgName + imgType;//服务器端路径          
            int IType = 0;
            IType = formatFileType(imgType);  //转换文件类型为对应 的数字   
            string uploadPath = "";
            uploadPath = Server.MapPath(FilePath + CurrentUserCode + "/UploadFile/");//物理存储路径
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                HttpPostedFile file = files.Get(0);
                Stream stream = file.InputStream;
                byte[] stbyte = new byte[stream.Length];
                stream.Read(stbyte, 0, stbyte.Length);
                stream.Seek(0, SeekOrigin.Begin);//从0字节开始读取流
                try
                {
                    //若不存在当前目录则创建
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }

                    int size = (int)stream.Length / 1024;//计算当前上传文件的大小(KB)

                    //流存储
                    using (var inputStream = stream)
                    {
                        using (var flieStream = new FileStream(Server.MapPath(webFile), FileMode.Create))
                        {
                            inputStream.CopyTo(flieStream);
                        }
                    }


                    //先将文件插入到 CommonFiles表中
                    TbCommonFiles tempTF = new TbCommonFiles();
                    tempTF.SFileName = name;
                    tempTF.SSaveName = imgName + imgType;
                    tempTF.SUrl = webFile;
                    tempTF.ISize = size;
                    tempTF.IType = IType;
                    tempTF.SMd5 = Md5Str;
                    tempTF.ICount = 1;
                    CommonFilesDAO CFDAO = new CommonFilesDAO();
                    CFDAO.Insert(tempTF);

                    //插入到数据库
                    TbTeaSource source = new TbTeaSource();
                    source.SSourceName = name;
                    source.IType = IType;
                    source.SSaveName = imgName + imgType;
                    source.SUrl = webFile;//相对路径
                    source.ISize = size;
                    source.DCreate = DateTime.Now;//获取系统当前时间

                    //修正文件夹的路径不对的问题
                    int newDictID = int.Parse(frontCurrentTea.GetCurrentDictID().ToString());
                    if (newDictID == 0)
                    {
                        source.ITeaSourceDictId = DictID;
                    }
                    else
                    {
                        source.ITeaSourceDictId = newDictID;
                    }
                    // end 修正

                    source.IOwnerUserId = CurrentUserID;
                    source.SOwnerName = CurrentUserName;
                    source.IFileId = int.Parse(tempTF.Id.ToString());
                    teaSourceDAO.Insert(source);

                    //若果上传的是Word，Excel,PPT文件，则生成预览文件".htm"
                    OfficeHelper.ShowOfficeDoc(webFile);

                }
                catch (Exception e)
                {
                    throw e;
                }
            }

        }




        /// <summary>
        /// 转换文件的扩展名为对应的数字，存储到数据库
        /// </summary>
        /// <param name="ExtensionName"></param>
        /// <returns></returns>
        public int formatFileType(string ExtensionName)
        {
            int IType = 0;  //返回值的类型

            switch (ExtensionName)
            {
                case ".doc":
                case ".docx":
                case ".docm":
                    IType = 1;
                    break;
                case ".xls":
                case ".xlsx":
                    IType = 2;
                    break;
                case ".jpeg":
                case ".jpg":
                case ".gif":
                case ".png":
                    IType = 6;
                    break;
                case ".pptx":
                case ".ppt":
                    IType = 3;
                    break;
                case ".rar":
                    IType = 4;
                    break;
                case ".zip":
                    IType = 5;
                    break;
                case ".mp3":
                case ".wav":

                    IType = 7;
                    break;
                default:
                    break;
            }
            return IType;
        }



        #endregion



        /*--------------------上面是私人资源----------------------------------下面是公开资源-------------------*/



        #region 课程教学资源管理
        /// <summary>
        /// 合并文件和文件夹
        /// </summary>
        /// <param name="IParentId">当前父节点下的所有</param>
        /// <returns></returns>
        public List<PublicResource> MergePublic(int IParentId, int CourseID, int TeaID = 0, int IPublic = 0)
        {
            List<PublicResource> list = new List<PublicResource>();
            //获取当前文件夹下的文件夹
            int id = TeaID == 0 ? CurrentUserID : TeaID;
            string whereClase = IPublic == 0 ? "I_ParentId=" + IParentId
                + " and I_OwnerUserID=" + id
                + " and I_CourseID = " + CourseID :
                "I_ParentId=" + IParentId
                + " and I_OwnerUserID=" + id
                + " and I_CourseID = " + CourseID + " and I_Public = 1";
            TList<TbTeaPublicSourceDict> DictList = teaPublicSourceDictDAO.GetByPage(whereClase, 0, int.MaxValue);
            foreach (var item in DictList)
            {
                PublicResource temp = new PublicResource();
                //将每个文件夹添加到新类列表
                temp.Id = item.Id;
                temp.IParentId = (int)item.IParentId;
                temp.ILevel = (int)item.ILevel;
                temp.IOwnerUserId = CurrentUserID;
                temp.SSourceName = item.SDicName;
                temp.FileType = 0;
                temp.IPublic = item.IPublic;
                temp.ICourseId = item.ICourseId;
                list.Add(temp);
            }

            //查找当前文件夹下的文件,若在最顶层,IPublic = 0；
            whereClase = IPublic == 0 ? "I_TeaPublicDictID=" + IParentId + " and I_CourseID = " + CourseID :
                "I_TeaPublicDictID=" + IParentId + " and I_Public = 1" + " and I_CourseID = " + CourseID;
            TList<TbTeaPublicSource> SourceList = teaPublicSourceDAO.GetByPage(whereClase, 0, int.MaxValue);
            foreach (var ite in SourceList)
            {
                //将每个文件添加到新类列表
                PublicResource temp1 = new PublicResource();
                ClassValueCopier.Copy(temp1, ite);
                temp1.IParentId = (int)ite.ITeaPublicDictId;
                temp1.FileType = 1;
                list.Add(temp1);
            }

            return list;
        }




        /// <summary>
        /// 重载MergePublic
        /// </summary>
        /// <param name="dictList">目录列表</param>
        /// <param name="sourList">文件列表</param>
        /// <returns></returns>
        public List<PublicResource> MergePublic(TList<TbTeaPublicSourceDict> dictList, TList<TbTeaPublicSource> sourList)
        {
            List<PublicResource> list = new List<PublicResource>();
            //遍历所有文件夹
            foreach (var item in dictList)
            {
                PublicResource temp = new PublicResource();
                //将每个文件夹添加到新类列表
                temp.Id = item.Id;
                temp.IParentId = (int)item.IParentId;
                temp.ILevel = (int)item.ILevel;
                temp.IOwnerUserId = CurrentUserID;
                temp.SSourceName = item.SDicName;
                temp.FileType = 0;
                temp.IPublic = item.IPublic;
                temp.ICourseId = item.ICourseId;
                list.Add(temp);
            }
            //遍历所有文件
            foreach (var ite in sourList)
            {
                //将每个文件添加到新类列表
                PublicResource temp1 = new PublicResource();
                ClassValueCopier.Copy(temp1, ite);
                temp1.IParentId = (int)ite.ITeaPublicDictId;
                temp1.FileType = 1;
                list.Add(temp1);
            }
            return list;
        }




        /// <summary>
        /// 获取当期文件夹下的所有
        /// </summary>
        /// <param name="ID">当期文件夹的ID</param>
        /// <returns></returns>
        public JsonResult GetPublicFile(string SourceName, int CourseID, int ID = 0, int IParentID = -1)
        {
            List<PublicResource> userList = new List<PublicResource>();

            int id = IParentID == -1 ? ID : IParentID;

            if (string.IsNullOrEmpty(SourceName))
            {
                if (id == 0)
                {
                    //取得根目录下的文件
                    TList<TbTeaPublicSource> sourList = teaPublicSourceDAO.GetByPage(
                        "I_TeaPublicDictID=0 and I_CourseID=" + CourseID + "and I_OwnerUserID=" + CurrentUserID, 0, int.MaxValue);
                    //取根目录下的文件夹
                    TList<TbTeaPublicSourceDict> dictList = teaPublicSourceDictDAO.GetByPage(
                        "I_ParentID=0 and I_CourseID=" + CourseID + "and I_OwnerUserID=" + CurrentUserID, 0, int.MaxValue);
                    userList = MergePublic(dictList, sourList);
                }
                else
                    userList = MergePublic(id, CourseID);
            }
            else
            {
                //模糊查询文件夹
                string whereClause1 = "S_DicName like '%" + SourceName + "%' and I_OwnerUserID =" + CurrentUserID;
                TList<TbTeaPublicSourceDict> dictList = teaPublicSourceDictDAO.GetByPage(whereClause1, 0, int.MaxValue);

                //模糊查询文件
                string whereClause2 = "S_SourceName like '%" + SourceName + "%'and I_OwnerUserID =" + CurrentUserID;
                TList<TbTeaPublicSource> sourList = teaPublicSourceDAO.GetByPage(whereClause2, 0, int.MaxValue);

                userList = MergePublic(dictList, sourList);
            }
            return Json(new
            {
                Data = userList
            }, JsonRequestBehavior.AllowGet);
        }



        /// <summary>
        /// 返回上一级
        /// </summary>
        /// <param name="IParentID"></param>
        /// <param name="ID"></param>
        /// <returns></returns>
        public JsonResult PublicGoToParent(int CourseID, int IParentID = -1, int ID = 0)
        {
            //若最后一层，记录下当前文件夹的ID
            if ((IParentID == -1) || (IParentID == 0 && ID != 0))
                IParentID = ID;
            //若在0层，返回空
            else if (IParentID == 0)
                return Json(null);
            //查找父文件夹
            TbTeaPublicSourceDict dict = teaPublicSourceDictDAO.GetByID(IParentID);

            //得到父文件夹的IParentId
            int id = dict != null ? int.Parse(dict.IParentId.ToString()) : 0;
            //得到同一文件夹下的 文件和文件夹
            var userList = MergePublic(id, CourseID);
            return Json(new
            {
                Data = userList
            }, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 文件夹和文件的删除,只删除数据库中的数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int DeletePublicFile(string ids)
        {
            try
            {
                if (string.IsNullOrEmpty(ids))
                    return 1;
                string[] str = ids.Split(new char[] { ',' });
                //拆分字符串，判断文件夹，文件
                foreach (var item in str)
                {
                    if (item.Equals("0"))
                        continue;
                    string[] FileInfro = item.Split(new char[] { ':' });
                    int id = int.Parse(FileInfro[0]);
                    if (FileInfro[1].Equals("0"))//文件夹
                    {
                        //删除文件夹
                        DeleteFiles(id);

                    }
                    else
                    {
                        TbTeaPublicSource source = teaPublicSourceDAO.GetByID(id);
                        teaPublicSourceDAO.Del(id);//删除文件
                    }
                }
                return 1;
            }
            catch (Exception e)
            {

                return 0;
            }
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="id"></param>
        public void DeleteFiles(int id)
        {
            teaPublicSourceDictDAO.Del(id);
            //删除当期文件夹下的文件
            TList<TbTeaPublicSource> source = teaPublicSourceDAO.GetByPage("I_TeaPublicDictID=" + id, 0, int.MaxValue);
            teaPublicSourceDAO.Del(source);
            //删除当期文件夹下的文件夹
            TList<TbTeaPublicSourceDict> dict = teaPublicSourceDictDAO.GetByPage("I_ParentID=" + id, 0, int.MaxValue);
            if (dict.Count == 0)
                return;
            else
            {
                teaPublicSourceDictDAO.Del(dict);
                foreach (var item in dict)
                {
                    DeleteFiles(item.Id);
                }
            }
        }


        /// <summary>
        /// 添加文件夹
        /// </summary>
        /// <param name="SSourceName"></param>
        /// <param name="IParentId"></param>
        /// <param name="ILevel"></param>
        /// <param name="IOwnerUserID"></param>
        /// <returns></returns>
        public int AddPublicFile(string SSourceName, int Id, int IParentId, int ILevel, int ICourseID)
        {

            if (ILevel == 0)
            {   //0层以下只有文件或空文件夹时
                TbTeaPublicSourceDict dict = teaPublicSourceDictDAO.GetByID(Id);
                if (dict == null)
                {//文件夹已全部删除，新增到0层
                    IParentId = 0;
                    ILevel = 1;
                }
                else
                {
                    ILevel = (int)dict.ILevel + 1;
                }             
            }
            try
            {
                TbTeaPublicSourceDict Dict = new TbTeaPublicSourceDict();
                Dict.SDicName = SSourceName;
                Dict.IParentId = IParentId;
                Dict.ILevel = ILevel;
                Dict.IOwnerUserId = CurrentUserID;
                Dict.IPublic = 0;
                Dict.ICourseId = ICourseID;
                teaPublicSourceDictDAO.Insert(Dict);
                return 1;
            }
            catch (Exception e)
            {

                return 0;
            }
        }




        /// <summary>
        /// 获取当前节点信息
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public JsonResult currentPublicFile(string keys)
        {
            string[] NodeInfo = keys.Split(new char[] { ':' });
            int id = int.Parse(NodeInfo[0]);
            PublicResource temp = new PublicResource();
            if (NodeInfo[1].Equals("0"))//文件夹
            {
                //找到当前文件夹
                TbTeaPublicSourceDict dict = teaPublicSourceDictDAO.GetByID(id);
                temp.Id = dict.Id;
                temp.IParentId = (int)dict.IParentId;
                temp.ILevel = (int)dict.ILevel;
                temp.IOwnerUserId = CurrentUserID;
                temp.SSourceName = dict.SDicName;
                temp.IPublic = dict.IPublic;
                temp.ICourseId = dict.ICourseId;
                temp.FileType = 0;
            }
            else
            {          //找到当前文件
                TbTeaPublicSource source = teaPublicSourceDAO.GetByID(id);
                ClassValueCopier.Copy(temp, source);
                temp.FileType = 1;
            }
            return Json(temp, JsonRequestBehavior.AllowGet);
        }



        /// <summary>
        /// 更新节点
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="res"></param>
        /// <returns></returns>
        public int UpdatePublicFileName(string keys, PublicResource res)
        {
            try
            {
                if (res.FileType == 0)//文件夹
                {
                    TbTeaPublicSourceDict dict = new TbTeaPublicSourceDict();
                    dict.Id = res.Id;
                    dict.IParentId = (int)res.IParentId;
                    dict.ILevel = (int)res.ILevel;
                    dict.IOwnerUserId = CurrentUserID;
                    dict.SDicName = res.SSourceName;
                    dict.ICourseId = res.ICourseId;
                    dict.IPublic = res.IPublic;
                    teaPublicSourceDictDAO.Update(dict);
                }
                else
                {
                    TbTeaPublicSource source = new TbTeaPublicSource();
                    ClassValueCopier.Copy(source, res);
                    teaPublicSourceDAO.Update(source);
                }
                return 1;
            }
            catch (Exception e)
            {

                return 0;
            }
        }

        /// <summary>
        /// 导入到教学资源
        /// </summary>
        /// <param name="FileType"></param>
        /// <returns></returns>
        public int LeadingIn(string FileType, int ICourseId, int Catalog = 0)
        {
            string[] file = FileType.Split(new char[] { ',' });//拆分文件
            foreach (var item in file)
            {
                string[] type = item.Split(new char[] { ':' });//判断文件类型
                if (type[1].Equals("1"))//单个文件处理
                {
                    int sourceId = int.Parse(type[0]);//选中的文件ID
                    // 找到当前文件
                    TbTeaSource teaSource = teaSourceDAO.GetByID(sourceId);
                    int parentId = (int)teaSource.ITeaSourceDictId;
                    TbTeaPublicSource temp = new TbTeaPublicSource();
                    ClassValueCopier.Copy(temp, teaSource);//拷贝属性
                    temp.Id = new int();//将原来的ID置空
                    temp.IPublic = 0;
                    temp.ICourseId = ICourseId;
                    temp.ITeaPublicDictId = Catalog;//教学平台的目录
                    temp.ITeaSourceId = sourceId;
                    temp.IIsDownload = 1;//默认允许下载
                    teaPublicSourceDAO.Insert(temp);//插入数据库
                }
                else
                {   //找到当前文件夹ID                   
                    int id = int.Parse(type[0]);
                    CopyFile(id, Catalog, ICourseId);//导入文件夹                    
                }
            }
            return 1;
        }

        /// <summary>
        /// 导入文件夹
        /// </summary>
        /// <param name="id"></param>
        public void CopyFile(int id, int Catalog, int ICourseId)
        {
            TbTeaSourceDict Dict = teaSourceDictDAO.GetByID(id);
            TbTeaPublicSourceDict temp = new TbTeaPublicSourceDict();
            ClassValueCopier.Copy(temp, Dict);//拷贝属性
            temp.Id = new int();//将原来的ID置空
            temp.IPublic = 0;
            temp.IParentId = Catalog;
            temp.ICourseId = ICourseId;
            if (Catalog == 0)
                temp.ILevel = 1;
            else
            {
                int level = (int)teaPublicSourceDictDAO.GetByID(Catalog).ILevel + 1;
                temp.ILevel = level;
            }
            teaPublicSourceDictDAO.Insert(temp);//插入数据库
            //找到当前文件夹下的文件
            TList<TbTeaSource> fileList = teaSourceDAO.GetByPage("I_TeaSourceDictID=" + id, 0, int.MaxValue);
            foreach (var itemFile in fileList)
            {
                TbTeaPublicSource temp1 = new TbTeaPublicSource();
                ClassValueCopier.Copy(temp1, itemFile);//拷贝属性
                temp1.Id = new int();//将原来的ID置空
                temp1.IPublic = 0;
                temp1.ICourseId = ICourseId;//加上课程ID
                temp1.ITeaPublicDictId = temp.Id;//当前文件夹的ID
                temp1.ITeaSourceId = itemFile.Id;//当前文件夹下的文件的ID
                temp1.IIsDownload = 1;//默认允许下载
                teaPublicSourceDAO.Insert(temp1);//插入数据库
            }
            TList<TbTeaSourceDict> listDict = teaSourceDictDAO.GetByPage("I_ParentID=" + id, 0, int.MaxValue);
            if (listDict.Count == 0)
                return;
            else
            {   //若文件夹下还有文件夹，
                foreach (var item in listDict)
                {
                    //temp.Id为父节点

                    CopyFile(item.Id, temp.Id, ICourseId);
                }
            }
        }




        /// <summary>
        /// 文件夹不公开，若里面文件/文件夹公开，将此文件夹公开，但文件夹内的其他函数不公开
        /// </summary>
        /// <param name="id"></param>
        public void OnlyChangeStatefiles(int id)
        {
            if (id == 0)
                return;
            TbTeaPublicSourceDict dict = teaPublicSourceDictDAO.GetByID(id);
            if (dict.IPublic == 0)
            {
                dict.IPublic = 1;
            }
            teaPublicSourceDictDAO.Update(dict);
            if (dict.IParentId == 0)
                return;
            else
            {
                OnlyChangeStatefiles((int)dict.IParentId);
            }
        }


        /// <summary>
        /// 改变状态
        /// </summary>
        /// <param name="id">选择文件ID</param>
        /// <param name="fileType">文件，或文件夹</param>
        public void ChangeState(int id, int fileType)
        {
            if (fileType == 1)//单个文件
            {
                TbTeaPublicSource source = teaPublicSourceDAO.GetByID(id);
                //当前状态
                int state = (int)source.IPublic;
                //改变状态
                source.IPublic = Math.Abs(state - 1);
                teaPublicSourceDAO.Update(source);
                OnlyChangeStatefiles((int)source.ITeaPublicDictId);
            }
            else
            {
                TbTeaPublicSourceDict dict = teaPublicSourceDictDAO.GetByID(id);
                int state = (int)dict.IPublic;
                dict.IPublic = Math.Abs(state - 1);
                ChangeStatefiles(id, (int)dict.IPublic);//改变对象为文件夹
                int parentId = (int)teaPublicSourceDictDAO.GetByID(id).IParentId;
                if (parentId == 0)
                    return;
                else
                    OnlyChangeStatefiles(parentId);
            }
        }

        /// <summary>
        /// 改变文件夹的状态
        /// </summary>
        /// <param name="id"></param>
        public void ChangeStatefiles(int id, int IPublic)
        {
            //改变当前文件夹的状态
            TbTeaPublicSourceDict dict = teaPublicSourceDictDAO.GetByID(id);
            dict.IPublic = IPublic;
            teaPublicSourceDictDAO.Update(dict);


            //改变文件夹下，文件的状态
            TList<TbTeaPublicSource> sourceList = teaPublicSourceDAO.GetByPage("I_TeaPublicDictID=" + id, 0, int.MaxValue);
            foreach (var item in sourceList)
            {
                item.IPublic = dict.IPublic;//文件状态与文件夹一致
            }
            teaPublicSourceDAO.Update(sourceList);//更新到数据库
            //当前文件夹下的文件夹
            TList<TbTeaPublicSourceDict> dictList = teaPublicSourceDictDAO.GetByPage("I_ParentID=" + id, 0, int.MaxValue);
            if (dictList.Count != 0)
            {   //若存在文件夹
                foreach (var item in dictList)
                {
                    ChangeStatefiles(item.Id, IPublic);
                }
            }
            else
                return;
        }



        /// <summary>
        /// 学生端获取当期文件夹下的所有
        /// </summary>
        /// <param name="ID">当期文件夹的ID</param>
        /// <returns></returns>
        public JsonResult StuGetPublicFile(string SourceName, int CourseID, int TeaID, int ID = 0, int IParentID = -1)
        {
            List<PublicResource> userList = new List<PublicResource>();

            int id = IParentID == -1 ? ID : IParentID;

            if (string.IsNullOrEmpty(SourceName))
            {
                if (id == 0)
                {
                    //取得根目录下的文件
                    TList<TbTeaPublicSource> sourList = teaPublicSourceDAO.GetByPage(
                        "I_TeaPublicDictID=0 and I_CourseID=" + CourseID
                        + "and I_OwnerUserID=" + TeaID
                        + "and I_Public = 1", 0, int.MaxValue);
                    TList<TbTeaPublicSourceDict> dictList = teaPublicSourceDictDAO.GetByPage(
                        "I_ParentID=0 and I_CourseID=" + CourseID
                        + "and I_OwnerUserID=" + TeaID
                        + "and I_Public = 1", 0, int.MaxValue);
                    userList = MergePublic(dictList, sourList);
                }
                else
                    userList = MergePublic(id, CourseID, TeaID, 1);
            }
            else
            {
                //模糊查询文件夹
                string whereClause1 = "S_DicName like '%" + SourceName + "%' and I_OwnerUserID =" + TeaID + "and I_Public=1";
                TList<TbTeaPublicSourceDict> dictList = teaPublicSourceDictDAO.GetByPage(whereClause1, 0, int.MaxValue);

                //模糊查询文件
                string whereClause2 = "S_SourceName like '%" + SourceName + "%'and I_OwnerUserID =" + TeaID + "and I_Public=1";
                TList<TbTeaPublicSource> sourList = teaPublicSourceDAO.GetByPage(whereClause2, 0, int.MaxValue);

                userList = MergePublic(dictList, sourList);
            }
            return Json(new
            {
                Data = userList
            }, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 返回上一级
        /// </summary>
        /// <param name="IParentID"></param>
        /// <param name="ID"></param>
        /// <returns></returns>
        public JsonResult StuPublicGoToParent(int CourseID, int TeaID, int IParentID = -1, int ID = 0)
        {
            //若最后一层，记录下当前文件夹的ID
            if ((IParentID == -1) || (IParentID == 0 && ID != 0))
                IParentID = ID;
            //若在0层，返回空
            else if (IParentID == 0)
                return Json(null);
            //查找父文件夹
            TbTeaPublicSourceDict dict = teaPublicSourceDictDAO.GetByID(IParentID);

            //得到父文件夹的IParentId
            int id = int.Parse(dict.IParentId.ToString());

            //得到同一文件夹下的 文件和文件夹
            var userList = MergePublic(id, CourseID, TeaID, 1);
            return Json(new
            {
                Data = userList
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 改变下载权限
        /// </summary>
        /// <param name="id"></param>
        /// <param name="fileType"></param>
        public void ChangePower(int id, int fileType)
        {
            if (fileType == 1)//单个文件
            {
                TbTeaPublicSource source = teaPublicSourceDAO.GetByID(id);
                //当前状态
                int power = (int)source.IIsDownload;
                //改变状态
                source.IIsDownload = Math.Abs(power - 1);
                teaPublicSourceDAO.Update(source);
            }
            else
                return;
        }


        #endregion

    }
}